#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from MakeExcel import MakeExcel
from ParseXml import ParseXml
import os
import sys

xml_file_name_list = ['activity.xml', 'objects.xml', 'shop.xml', 'disgift.xml', 'giftbox.xml', 'drops.xml',
                      'sequence.xml', 'ShopConfig.xml', 'ActivityConfig.xml', 'PreviewConfig.xml',
                      'TimeShopConfig.xml']
root_path = os.path.dirname(os.path.abspath(__file__))


def make_excel(excel_object, sheet_name, current_row, root_element):
    if excel_object.file_name == 'ActivityConfig.xlsx':
        element_list = ParseXml.specific_divide_element_list(root_element)
    else:
        element_list = ParseXml.divide_element_list(root_element)
    for sub_list in element_list:
        # print('-' * 100)
        typ = ParseXml.get_element_type(sub_list[0])
        if typ == 'Commentary':
            for element in sub_list:
                if ParseXml.get_element_type(element) == 'Commentary':
                    cmt = ParseXml.get_comment_text(element)
                    excel_object.make_comment(sheet_name, current_row, cmt)
                    # print('=>', current_row, cmt)
                    current_row += 1
        elif typ == 'Element':
            attr_group = [ParseXml.get_element_attributes(element) for element in sub_list]
            new_row = excel_object.make_elements(sheet_name, current_row, attr_group)
            # print('@@', '{0}~{1}'.format(current_row, current_row + len(attr_group)), attr_group)
            current_row = new_row + 2


for root, dirs, files in os.walk(root_path):
    for file in files:
        if file in xml_file_name_list:
            xml_path = os.path.join(root, file)
            xml_obj = ParseXml(xml_path)

            excel_name = str(file.split('.')[0]) + '.xlsx'
            excel_path = os.path.join(root, excel_name)
            excel_sheet_name = 'Sheet1'

            if os.path.exists(excel_path):
                try:
                    excel_obj = MakeExcel(excel_path)
                    row = 1
                    el_list = xml_obj.get_element_list(xml_obj.root)
                    make_excel(excel_obj, excel_sheet_name, row, el_list)
                    excel_obj.save_workbook()
                except Exception:
                    print('Xml文档[{0}]生成Xlsx表格失败'.format(xml_path))
                else:
                    print('Xml文档[{0}]生成Xlsx表格成功'.format(xml_path))
            else:
                print('Xlsx表格[{0}]不存在，请新建'.format(excel_path))

print('')
print('-' * 100)
string = input('请按任意键关闭控制台')
if string:
    sys.exit(0)
